import json
import random
import time
import requests

from django.views import View
from django.http import JsonResponse, HttpResponse

from apps.verifications.tools import generate_captcha
from django_redis import get_redis_connection
from md_sc.config import REDIS_KEY_MAP

from celery_tasks.sms.tasks import send_msg


# Create your views here.

class ImageCodeView(View):

    def get(self, request, uuid):
        text, image = generate_captcha()

        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex(REDIS_KEY_MAP.get('ImageCode') + str(uuid), 300, text)

        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        data = request.GET
        redis_conn = get_redis_connection('verify_code')
        img_code = redis_conn.get(REDIS_KEY_MAP.get('ImageCode') + str(data.get('image_code_id')))

        if not img_code or img_code.decode() != data.get('image_code'):
            return JsonResponse({'code': 4000, 'errmsg': '验证码失效'})

        # 发送短信验证码
        # msg_code = random.randint(1000, 9999)
        # ret = send(mobile=[mobile], code=msg_code)
        # print(ret)
        # redis_conn.setex(REDIS_KEY_MAP.get('SmsCode') + mobile, 300, str(msg_code))
        # redis_conn.delete(REDIS_KEY_MAP.get('ImageCode') + str(data.get('image_code_id')))

        # 线程发送

        # task = Thread(target=send_msg, args=(mobile, data.get('image_code_id')))
        # task.start()

        #celery 发送

        redis_conn = get_redis_connection('verify_code').pipeline()
        msg_code = random.randint(1000, 9999)
        redis_conn.setex(REDIS_KEY_MAP.get('SmsCode') + mobile, 300, str(msg_code))
        redis_conn.delete(REDIS_KEY_MAP.get('ImageCode') + str(data.get('image_code_id')))
        redis_conn.execute()

        send_msg.delay(mobile, msg_code)

        url = 'https://oapi.dingtalk.com/robot/send?access_token=e6a9e6a96398b54f8b674f42cf908cfc54adc5f9a83226c0ad2d7056c810a9de'
        ret = requests.post(url, json={
            "text": {
                "content": f"{mobile}的 验证码:{msg_code}"
            },
            "msgtype": "text"
        })
        return JsonResponse({'code': 0, 'errmsg': '短信发送成功'})


# def send_msg(mobile, uuid):
#     redis_conn = get_redis_connection('verify_code')
#     pl = redis_conn.pipeline()
#
#     msg_code = random.randint(1000, 9999)
#     print(mobile, msg_code)
#     ret = send(mobile=[mobile], code=msg_code)
#     print(ret)
#     pl.setex(REDIS_KEY_MAP.get('SmsCode') + mobile, 300, str(msg_code))
#     pl.delete(REDIS_KEY_MAP.get('ImageCode') + str(uuid))
#     pl.execute()
